package com.xjh.him.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.EncryptUtils;
import com.xjh.him.constant.Constant;
import com.xjh.him.dao.UserMapper;
import com.xjh.him.domain.UserDO;
import com.xjh.him.dto.user.UserDTO;
import com.xjh.him.dto.user.UserLoginDTO;
import com.xjh.him.dto.user.UserLoginResultDTO;
import com.xjh.him.netty.HandlerListener;
import com.xjh.him.netty.NettyCore;
import com.xjh.him.util.JwtUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xjh.tool.Checks;
import org.xjh.tool.common.ErrorMsg;
import org.xjh.tool.dto.ResultDTO;

@Slf4j
@Service
public class UserServiceImpl implements IUserService, HandlerListener {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultDTO<UserLoginResultDTO> login(UserLoginDTO loginDTO) {
        if (Checks.isAnyEmpty(loginDTO, loginDTO.getPhone(), loginDTO.getPassword())) {
            return ResultDTO.getFailureResult(ErrorMsg.ERR_PARAMETER_IS_NULL);
        }
        String raw = Constant.ENCRYPT_PWD_SALT_PREFIX + loginDTO.getPassword();
        String encryptPwd = EncryptUtils.md5Base64(raw);

        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", loginDTO.getPhone());
        UserDO userDO = userMapper.selectOne(queryWrapper);
        if (userDO != null) {
            //登录
            if (!userDO.getPassword().equals(encryptPwd)) {
                return ResultDTO.getFailureResult("手机号或密码错误");
            }
        }else {
            //注册
            userDO = new UserDO();
            userDO.setPhone(loginDTO.getPhone());
            userDO.setPassword(encryptPwd);
            userDO.setAvatarUrl("https://tva4.sinaimg.cn/large/9bd9b167ly1g1p9qik4lij20b40b4aaz.jpg");
            int insert = userMapper.insert(userDO);
            if (insert == 0) {
                return ResultDTO.getFailureResult(ErrorMsg.ERR_SYSTEM_BUSY);
            }
        }
        //返回token
        UserLoginResultDTO userLoginResultDTO = new UserLoginResultDTO();
        UserDTO userDTO = new UserDTO();
        userLoginResultDTO.setUserDTO(userDTO);
        String token = JwtUtil.getToken(userDO);
        userLoginResultDTO.setToken(token);
        BeanUtils.copyProperties(userDO, userDTO);
        return ResultDTO.getSuccessResult(userLoginResultDTO);
    }

    @Override
    public ResultDTO<Boolean> updateInfo(UserDTO userDTO) {
        if (Checks.isAnyEmpty(userDTO, userDTO.getId())) {
            return ResultDTO.getFailureResult("用户id不能为空");
        }
        log.info("userDTO:{}", userDTO);
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userDTO, userDO);
        Integer updateInfo = userMapper.updateInfo(userDO);
        if (updateInfo == 0) {
            return ResultDTO.getFailureResult(ErrorMsg.ERR_SYSTEM_BUSY);
        }
        return ResultDTO.getSuccessResult(true);
    }

    @Override
    public ResultDTO<UserDTO> findUser(Long id) {
        if (Checks.isEmpty(id)) {
            return ResultDTO.getFailureResult("用户id不能为空");
        }
        UserDO userDO = userMapper.selectById(id);
        if (userDO == null) {
            return ResultDTO.getFailureResult("用户不存在");
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userDO, userDTO);
        return ResultDTO.getSuccessResult(userDTO);
    }

    @Override
    public Boolean consume(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof Long) {
            Long userId = (Long) msg;
            UserDO userDO = userMapper.selectById(userId);
            ctx.channel().attr(NettyCore.CHANNEL_KEY).set(userDO);
            NettyCore.ACTIVE_USER_CHANNEL.put(userId, ctx.channel());
            log.info("userId:{} register channel", userId);
            return true;
        }

        return false;
    }
}
